/**
 * @Author ouxueting
 */
package com.chinaunicom.tour.sys.controller;

import com.chinaunicom.tour.sys.constant.ResultConstants;
import com.chinaunicom.tour.sys.util.ObjectRestResponse;
import com.chinaunicom.tour.sys.util.VerificationCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

@Api(value = "验证码", tags = { "验证码" })
@RestController
@RequestMapping("verification")
public class VerificationCodeController {

    @ApiOperation(value = "生成验证码", notes = "")
    @RequestMapping(value = "create", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<Character[]> verificationCodeCreate(HttpServletRequest request, HttpServletResponse response) {
        ObjectRestResponse<Character[]> orr = new ObjectRestResponse<Character[]>();
        HttpSession session = request.getSession();

      /*  response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        OutputStream os = null;*/
        try {
         //   os = response.getOutputStream();
            //返回验证码和图片的map
            Map<String,Object> map = VerificationCodeUtil.getImageCode(/*86, 37, os*/);
            session.setAttribute("verificationCode", map.get("strEnsure").toString());
            session.setAttribute("codeTime",new Date().getTime());

            orr.setStatus(ResultConstants.SUCCESS_CODE);
            orr.setMessage("验证码生成成功");
            char[]  ch = map.get("strEnsure").toString().toCharArray();
            Character[] str = new Character[4];
            str[0] = ch[0];
            str[1] = ch[1];
            str[2] = ch[2];
            str[3] = ch[3];
            orr.setData(str);
           // ImageIO.write((BufferedImage) map.get("image"), "jpg", os);
            return orr;

        } catch (Exception e) {
            orr.setStatus(ResultConstants.ERROR_CODE);
            orr.setMessage("验证码生成异常"+e.getMessage() );
            return orr;

        }  /* finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    orr.setStatus(ResultConstants.ERROR_CODE);
                    orr.setMessage("图片生成异常"+e.getMessage() );
                    return orr;
                }
            }
            return orr;
        }*/
    }

}
